<?php
/**
 * descript: 自定义异常处理器
 * User: blue
 * Date: 2018/5/7 10:58
 */
namespace app\lib\exception;
use think\Exception;
use think\exception\Handle;
use think\facade\Log;

class ExceptionHandler extends Handle {
    private $code;
    private $msg;
    private $errCode;
    //需要返回客户端当前请求的url路径
    /**
     * @param Exception $e
     * @return \think\Response|void
     */
    public function render(\Exception $e)
    {
        if($e instanceof BaseException){
        //    自定义的异常
            $this->code=$e->code;
            $this->msg=$e->msg;
            $this->errCode=$e->errCode;
        }else{
        // 系统的异常,判断是不是调试模式:是,显示tp5的异常,否则显示封装接口的异常
            if(config('app.app_debug')){
                //使用tp5默认的错误提示
               return parent::render($e);
            }else{
                $this->code=500;
                $this->msg='服务器内部错误';
                $this->errCode=999;
                //真是的错误写入日志
                // echo($e->getMessage());
                Log::record($e->getMessage(),'error');
            }
        }
        //返回错误数据
        $url=request()->url();
        $result=[
            'msg'=>$this->msg,
            'errCode'=>$this->errCode,
            'url'=>$url
        ];
        return json($result,$this->code);
    }
}